
import json
from flask import Flask, request

from conn_mysql import ConnectMysql
import pymysql

app = Flask(__name__)

import datetime

#json使用dumps对datatime不能序列化，重构json,调取时json.dumps(info, cls = DateEncoder)
class DateEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')

        elif isinstance(obj, datetime.date):
            return obj.strftime("%Y-%m-%d")

        else:
            return json.JSONEncoder.default(self, obj)


@app.route('/api/v1/company', methods = ['GET', 'POST'])

def company_api():

    con_obj = ConnectMysql()

    if request.method == 'GET':#查询company表的信息

        page = request.args.get('page')#如果没有page参数返回的是个None

        limit = request.args.get('limit')#每页几条数据

        if page == None:

            page = '1'

        if limit == None:

            limit = '20'

        if page.isdecimal() and limit.isdecimal(): #检查参数合法性

            page = int(page)
            limit = int(limit)

        else:
            con_obj.close()
            return {
                'status': -1,
                'errorCode': 'ValueError',
                'errorMsg':f'请检查page和limit参数是否合法,page:{page},limit:{limit}',
                'resultBody':''
            }

        sql = 'select * from company limit %s,%s'

        result_info = con_obj.select_all(sql, ((page-1)*limit, limit))

        con_obj.close()

        return {

            'status': 1,
            'errorCode': '',
            'errorMsg':'',
            'resultBody': json.dumps(result_info, cls=DateEncoder),
        }

    if request.method == 'POST':

        sql = '''INSERT INTO company
        (company_name, linkman, need, phone, party, residue_degree, pass_word)
        values
        (%s,%s,%s,%s,%s,%s,%s);       
        '''

        data_post = request.form

        info = (
            data_post.get('company_name'),
            data_post.get('linkman'),
            data_post.get('need'),
            data_post.get('phone'),
            data_post.get('party'),
            data_post.get('residue_degree'),
            data_post.get('pass_word'),
        )

        #pymysql.err.DataError: (1265, "Data truncated for column 'phone' at row 1")

        if all(info):

            try:

                con_obj.insert_info(sql, info)

            except pymysql.err.DataError as e:

                print(dir(e))

                print(e.args)#返回一个元组(1265, "Data truncated for column 'phone' at row 1")

                return {

                    'status': -1,
                    'errorCode': e.args[0],
                    'errorMsg':'pymysql.err.DataError:'+ e.args[1],
                    'resultBody': '',
                }

            else:

                return {

                    'status': 1,
                    'errorCode': '',
                    'errorMsg':'',
                    'resultBody': 'ok',
                }
            finally:
                con_obj.close()

        else:
            con_obj.close()
            return {

                    'status': -1,
                    'errorCode': '请检查你的值',
                    'errorMsg':'请检查你的值',
                    'resultBody': '',
                }


@app.route('/api/v1/company/<int:ID>', methods = ['GET', 'PUT', 'DELETE'])#作业

def company_api_id(ID):

    con_obj = ConnectMysql()

    if request.method =='GET':
        sql = 'SELECT * FROM company WHERE id = %s'
        info = con_obj.select_one(sql,(ID,))
        con_obj.close()

        if info:  #当info取到值时
            return {
                'status': 1,
                'errorCode': '',
                'errorMsg':'',
                'resultBody': json.dumps(info, cls=DateEncoder),
            }
        else:
            return {
                'status': -1,
                'errorCode': '数据库没有这个ID',
                'errorMsg':'数据库没有这个ID',
                'resultBody': '',
            }



if __name__ == '__main__':
    
    app.run(debug = True)
    